#pragma once
#include <iostream>
#include <string>
#include <map>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
using namespace std;

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4
#define BUFFER_SIZE 1024
#define Screen 1
#define Onefile 2
#define Classfile 3
#define LogFile "log.txt"

class Log
{
public:
  Log()
  {
    printMethod = Screen;
    path = "./log/";
  }

  string levelTostring(int level)
  {
    map<int, string> _map;
    _map[Info] = "Info";
    _map[Debug] = "Debug";
    _map[Warning] = "Warning";
    _map[Error] = "Error";
    _map[Fatal] = "Fatal";
    if (_map.find(level) != _map.end())
    {
      return _map[level];
    }
    return "";
  }

  void Enable(int method)
  {
    printMethod = method;
  }

  void printOneFile(const string &logname, const string &logtxt)
  {
    string _logname = path + logname;
    int fd = open(_logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
    if (fd < 0)
      return;
    write(fd, logtxt.c_str(), logtxt.size());
    close(fd);
  }

  void printClassFile(int level, const string &logtxt)
  {
    string filename = LogFile;
    filename += ".";
    filename += levelTostring(level);
    printOneFile(filename, logtxt);
  }

  void printLog(int level, const string &logtxt)
  {
    switch (printMethod)
    {
    case Screen:
      cout << logtxt << endl;
      break;
    case Onefile:
      printOneFile(LogFile, logtxt);
      break;
    case Classfile:
      printClassFile(level, logtxt);
      break;
    default:
      break;
    }
  }
  void operator()(int level, const char *format, ...)
  {
    time_t t = time(nullptr);
    struct tm *ctime = localtime(&t);

    char leftbuffer[BUFFER_SIZE];
    snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", levelTostring(level).c_str(),
             ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
             ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

    va_list s;
    va_start(s, format);
    char rightbuffer[BUFFER_SIZE];
    vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
    va_end(s);

    char logtxt[BUFFER_SIZE * 2];
    snprintf(logtxt, sizeof(logtxt), "%s %s\n", leftbuffer, rightbuffer);

    printLog(level, logtxt);
  }

  ~Log()
  {
  }

private:
  int printMethod;
  string path;
};
